package routers

import (
	"encoding/json"
	"fmt"
	"net/http"

	"gitee.com/kessil/chicory/internal/config"
	"gitee.com/kessil/chicory/internal/middleware"
	"gitee.com/kessil/chicory/internal/models"
	"gitee.com/kessil/chicory/internal/repositories"
	"gitee.com/kessil/chicory/internal/utils"
	"go.uber.org/zap"

	"github.com/go-chi/chi/v5"
	"xorm.io/xorm"
)

type AuthRouter struct {
	db   *xorm.Engine
	cfg  *config.Config
	repo *repositories.UserRepository
}

func NewAuthRouter(db *xorm.Engine, cfg *config.Config) *AuthRouter {
	return &AuthRouter{
		db:   db,
		cfg:  cfg,
		repo: repositories.NewUserRepository(db),
	}
}

func (ar *AuthRouter) Routes() chi.Router {
	r := chi.NewRouter()

	// 添加会话中间件到所有auth路由
	r.Use(middleware.SessionMiddleware)

	// 认证路由

	r.Group(func(protected chi.Router) {
		r.Post("/login", ar.login)
		r.Post("/register", ar.register)
		// 验证码路由 - 直接返回SVG图片
		r.Get("/captcha", ar.captcha)
		// 添加JWT认证中间件
		protected.Use(middleware.JWTAuthMiddleware(ar.cfg))
		r.Post("/logout", ar.logout)
	})

	return r
}

func (ar *AuthRouter) captcha(w http.ResponseWriter, r *http.Request) {
	// 获取当前会话
	session, exists := middleware.GetSessionFromRequest(r)
	if !exists {
		http.Error(w, "Session required", http.StatusBadRequest)
		return
	}

	// 生成验证码 - 使用优化版确保4个字符完全显示
	svgBytes, captchaCode := utils.GenerateOptimizedSVG(80, 40)

	// 将验证码存储到session中
	session.Data["captcha"] = captchaCode

	// 使用zap记录日志
	utils.Info("Generated captcha",
		zap.String("captcha", captchaCode),
		zap.String("session", session.ID))

	// 设置响应头，直接返回SVG图片
	// w.Header().Set("Content-Type", "image/svg+xml")
	w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
	w.Header().Set("Pragma", "no-cache")
	w.Header().Set("Expires", "0")
	w.Header().Set("Content-Type", "image/svg+xml; charset=utf-8")
	// 直接写入SVG内容
	w.Write(svgBytes)
}

func (ar *AuthRouter) login(w http.ResponseWriter, r *http.Request) {
	var loginReq models.LoginReq
	if err := json.NewDecoder(r.Body).Decode(&loginReq); err != nil {
		middleware.JSONError(w, http.StatusBadRequest, "Invalid request")
		return
	}

	// 验证验证码
	session, exists := middleware.GetSessionFromRequest(r)
	if !exists {
		middleware.JSONError(w, http.StatusBadRequest, "Session required")
		return
	}

	// 从session中获取验证码
	storedCaptcha, ok := session.Data["captcha"].(string)
	if !ok {
		middleware.JSONError(w, http.StatusBadRequest, "Captcha not found or expired")
		return
	}

	// 验证验证码
	if !utils.VerifyCaptcha(loginReq.Captcha, storedCaptcha) {
		middleware.JSONError(w, http.StatusBadRequest, "Invalid captcha")
		return
	}

	// 验证成功后删除验证码，防止重复使用
	delete(session.Data, "captcha")

	user, err := ar.repo.GetUserByUsername(loginReq.Username)
	if err != nil {
		middleware.JSONError(w, http.StatusInternalServerError, "Internal server error")
		return
	}

	if user == nil || !user.CheckPassword(loginReq.Password) {
		utils.Error(fmt.Sprintf("%v %v\n", user, user.CheckPassword(loginReq.Password)))
		middleware.JSONError(w, http.StatusUnauthorized, "Invalid credentials")
		return
	}

	token, err := models.GenerateJWT(user, ar.cfg.JWT.Secret, ar.cfg.JWT.Expire)
	if err != nil {
		middleware.JSONError(w, http.StatusInternalServerError, "Failed to generate token")
		return
	}
	// 用于接口测试
	// token = "access-token:admin:super-admin"

	middleware.JSONSuccess(w, map[string]interface{}{
		"accessToken": token,
		"originUrl":   "/auth/login",
	})
}

func (ar *AuthRouter) register(w http.ResponseWriter, r *http.Request) {
	var registerReq models.RegisterReq
	if err := json.NewDecoder(r.Body).Decode(&registerReq); err != nil {
		middleware.JSONError(w, http.StatusBadRequest, "Invalid request")
		return
	}

	// 验证验证码
	session, exists := middleware.GetSessionFromRequest(r)
	if !exists {
		middleware.JSONError(w, http.StatusBadRequest, "Session required")
		return
	}

	storedCaptcha, ok := session.Data["captcha"].(string)
	if !ok {
		middleware.JSONError(w, http.StatusBadRequest, "Captcha not found or expired")
		return
	}

	if !utils.VerifyCaptcha(registerReq.Captcha, storedCaptcha) {
		middleware.JSONError(w, http.StatusBadRequest, "Invalid captcha")
		return
	}

	// 验证成功后删除验证码
	delete(session.Data, "captcha")

	// 检查用户是否已存在
	existingUser, err := ar.repo.GetUserByUsername(registerReq.Username)
	if err != nil {
		middleware.JSONError(w, http.StatusInternalServerError, "Internal server error")
		return
	}

	if existingUser != nil {
		middleware.JSONError(w, http.StatusConflict, "Username already exists")
		return
	}

	// 创建新用户
	user := &models.User{
		Username: registerReq.Username,
	}

	// if err := user.SetPassword(registerReq.Password); err != nil {
	// 	middleware.JSONError(w, http.StatusInternalServerError, "Failed to set password")
	// 	return
	// }

	if err := ar.repo.Create(user); err != nil {
		middleware.JSONError(w, http.StatusInternalServerError, "Failed to create user")
		return
	}

	middleware.JSONSuccess(w, user)
}

func (ar *AuthRouter) logout(w http.ResponseWriter, r *http.Request) {
	middleware.JSONSuccess(w, true)
}
